/**
 * 
 */
define(function(require, exports, module){
    'use strict';
    var C = require('../config/const'),
    //require.async ('',function(js){})  异步加载
    alerts = require('../component/alerts'),
    FORCE_JSON = true;
    String.prototype.escapeHtml = function(){
        return this;
    } 
    String.prototype.toJSON = String.prototype.toJSON || function () {
        return this.escapeHtml();
    };
    function toParam(object) {
        if (object === undefined || object === null) {
            return null;
        }
      /*  if ($.isFunction(object.toJSON)) {
            object = object.toJSON();
        }
        for (var key in object) {
            if (object.hasOwnProperty(key)) {
                if (object[key] === null) {
                    delete object[key];
                } else if (typeof (object[key]) == "string") {
                    object[key] = object[key].toJSON().escapeHtml();
                } else {
                    object[key] = JSON.stringify(object[key]);
                    if (typeof (object[key]) == "string" && object[key].match(/^".*"$/)) {
                        object[key] = object[key].replace(/^"|"$/g, "");
                    }
                }
            }
        }*/
        return object;
    }
    function ajax(){
         var CODE_UNKNOWN = C.AJAX_CODE.UNKNOWN,
         CODE_OK = C.AJAX_CODE.OK,
         CODE_NO_DATA = C.AJAX_CODE.NO_DATA,
         CODE_PARA_ERROR = C.AJAX_CODE.PARA_ERROR,
         CODE_BACKEND_ERROR = C.AJAX_CODE.BACKEND_ERROR,
         CODE_LOGIN_REQUIRE = C.AJAX_CODE.LOGIN_REQUIRE,
         CODE_NO_RIGHT = C.AJAX_CODE.NO_RIGHT,
         CODE_NEED_JUMP = C.AJAX_CODE.NEED_JUMP,
         CODE_NEED_CONFIRM = C.AJAX_CODE.NEED_CONFIRM,
         MSG_UNKNOWN_ERROR = C.MESSAGE.UNKNOWN_ERROR,
         MSG_LOGIN_REQUIRE = C.MESSAGE.LOGIN_REQUIRE,
         MSG_LOGIN_REQUIRE_PROMPT = C.MESSAGE.LOGIN_REQUIRE_PROMPT,
         MSG_NO_RIGHT = C.MESSAGE.NO_RIGHT,
         CODE_NO_COMPANY = C.AJAX_CODE.CODE_NO_COMPANY,
         successHandler = function(){},
         errorHandler = function(c,m,d){
             if(c==11){
                 return window.parent.location = BASEPATH;
             }
             if(m!=undefined&&m!="")
                 alerts.show(m);
         },
         completeHandler = function(){},
         urlPost = "",
         dataPost = null,
         beforeSend = function (jqXHR, settings) {
         },
         success = function (data, textStatus, jqXHR) {
             var contentType = jqXHR.getResponseHeader("Content-Type").split(";")[0];
             if (FORCE_JSON || contentType === "application/json") {
                 if ($.isFunction(successHandler)) {
                     switch (data.code) {
                         case CODE_OK:
                         case CODE_NO_DATA:
                         case CODE_NEED_JUMP:
                         case CODE_LOGIN_REQUIRE:
                         case CODE_NO_COMPANY:
                             /*if(data.msg!=undefined&&data.msg!=''&&data.msg!='OK!'){
                                 alerts.show(data.msg);
                             }*/
                             if (data.code === CODE_NEED_JUMP) {
                                 try{
                                     if (undefind === data.data ||($.isNonEmptyString(data.data) && data.data.startsWith("/"))) {
                                             location.href = data.data;
                                     } else {
                                        location.href = "/";
                                     }
                                 }catch(e){
                                     location.href = "/";
                                 }
                             }
                             if (data.code === CODE_LOGIN_REQUIRE) {
                            	 if (CheckIsAndroid()) {//如果是Android
                            		 window.js.webNeedLogin();
                            	 }
                            	 if (CheckIsIOS()) {//如果是IOS
                            		 gotoIosFun();
                            	 }
                             }
                             successHandler(data.code, data.msg, data.data);

                             break;
                         case CODE_PARA_ERROR:
                         case CODE_BACKEND_ERROR:
                             errorHandler(data.code, data.msg, data.data);
                             break;
                         case CODE_NO_RIGHT:
                             errorHandler(data.code, data.msg, null);
                             break;
                         case CODE_NEED_CONFIRM:
                             errorHandler(data.code, data.msg, data.data);
                             break;
                         default:
                             alerts.alert(MSG_UNKNOWN_ERROR);
                             break;
                     }
                 }
             } else if (contentType === "text/html") {
                 data = data || "-1";
                 if (data.length < 10 && $.isNumeric(data)) {
                     errorHandler(parseInt(data, 10), null, null);
                 } else {
                     successHandler(CODE_OK, null, data);
                 }
             }
         },
         error = function (jqXHR, textStatus, errorThrown) {
             var contentType = jqXHR.getResponseHeader("Content-Type") && jqXHR.getResponseHeader("Content-Type").split(";")[0];
             if (textStatus === "abort") {
                 return;
             }
             if ($.isFunction(errorHandler)) {
                 errorHandler(CODE_UNKNOWN, MSG_UNKNOWN_ERROR, null);
             } else {
                 alerts.alert(MSG_UNKNOWN_ERROR);
             }
         },
         statusCode = {
         },
         complete = function (jqXHR, textStatus) {
             if ($.isFunction(completeHandler)) {
                 completeHandler(textStatus);
             }
         },_async=true,_contentType=undefined;
     this.sync = function(){
         _async = false;
         return this;
     }
     this.contentType=function(con){
         _contentType=con;
         return this;
     }
     this.success = function (fn) {
         successHandler = fn;
         return this;
     };
     this.error = function (fn) {
         errorHandler = fn;
         return this;
     };
     this.complete = function (fn) {
         completeHandler = fn;
         return this;
     };
     this.post = function (url, data,method) {
         if (!url || url.length === 0) {
             return null;
         }
         var typeMehod="POST";
         if(method!=null&& typeof method =="string"&&method.toLowerCase()=="get"){
             typeMehod="get";
         }
         urlPost = url;
         dataPost = toParam(data);
         var settings={
                 async: _async,
                 cache: false,
                 type: typeMehod,
                 url: urlPost,
                 dataType:"json",
                 data: dataPost,
                 beforeSend: beforeSend,
                 complete: complete,
                 error: error,
                 statusCode: statusCode,
                 success: success
             };
         if(_contentType){
             settings.contentType=_contentType;
         }
         try {
             return $.ajax(settings);
         } catch (e) {
             if ($.isFunction(completeHandler)) {
                 completeHandler("error");
             }
             if ($.isFunction(errorHandler)) {
                 errorHandler(CODE_UNKNOWN, MSG_UNKNOWN_ERROR);
             } else {
                 alerts.alert(MSG_UNKNOWN_ERROR);
             }
             return null;
         }
     };
    }
    function CheckIsIOS() {
        var browser = {
            versions: function () {
                var u = navigator.userAgent, app = navigator.appVersion;
                return { //移动终端浏览器版本信息 
                    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端 
                    android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器 
                    iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器 
                    iPad: u.indexOf('iPad') > -1, //是否iPad 
                };
            }(),
        }
        if (browser.versions.iPhone || browser.versions.iPad || browser.versions.ios) {
            return true;

            return false;
        }
    }
    function CheckIsAndroid() {
        var browser = {
            versions: function () {
                var u = navigator.userAgent, app = navigator.appVersion;
                return { //移动终端浏览器版本信息 
                    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端 
                    android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器 
                    iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器 
                    iPad: u.indexOf('iPad') > -1, //是否iPad 
                };
            }(),
        }
        if (browser.versions.android)
            return true;
        return false;
    }
    function gotoIosFun() {
    	window.onerror = function(err) {
    	}
    	function connectWebViewJavascriptBridge(callback) {
    		if (window.WebViewJavascriptBridge) {
    			callback(WebViewJavascriptBridge)
    		} else {
    			document.addEventListener('WebViewJavascriptBridgeReady', function() {
    				callback(WebViewJavascriptBridge)
    			}, false)
    		}
    	}
    	connectWebViewJavascriptBridge(function(bridge) {
    		bridge.init(function(message, responseCallback) {
    		})
    		var data = 'loginOut';
			bridge.send(data, function(responseData) {
			});
    	})
    }
    module.exports = {
            init: function () {
                return new ajax();
            }
        }
});